//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.IO;
using System.Security;
using System.Xml;
using CommunityServer.Components;

namespace CommunityServer.Blogs.Components
{
	/// <summary>
	/// Summary description for AutoBlogCreate.
	/// </summary>
	public class AutoBlogCreate : ICSModule
	{
		public AutoBlogCreate()
		{

		}

	    public void Init(CSApplication csa, XmlNode node)
	    {
            csa.PostUserUpdate +=new CSUserEventHandler(csa_PostUserUpdate);
        }

        private void csa_PostUserUpdate(User user, CSEventArgs e)
        {
            if(user != null && e.State == ObjectState.Create)
            {
                WeblogConfiguration config = WeblogConfiguration.Instance();
                if(config.EnableAutoCreate)
                {

                    string formattedKey = null;
                    Globals.ValidateApplicationKey(user.Username, out formattedKey);

                    if(Globals.IsNullorEmpty(formattedKey) || Weblogs.Exists(formattedKey, -1))
                    {
                        return;
                    }
                    Weblog w = new Weblog();
                    w.ApplicationKey = formattedKey;

                
                    int groupid = config.DefaultGroupID;
                    if(groupid <= 0)
                    {
                        ArrayList groups = WeblogGroups.GetWeblogGroups(true,false,false);
                        if(groups.Count > 0)
                            groupid = ((Group)groups[0]).GroupID;
                    }

                    if(groupid <=0)
                        return;
	
                    //Set remaining section settings
                    w.GroupID = groupid;
                    w.Name = user.Username;
                    w.IsActive = true;
                    w.SettingsID = CSContext.Current.SiteSettings.SettingsID;
                    w.ApplicationType = ApplicationType.Weblog;


                    w.Owners = user.Username;
                    w.IsSearchable =  true;
                    w.EnableAggBugs = true;
                    w.IsCommunityAggregated = true;

                    //Create The Blog
                    w.SectionID = Weblogs.Add(w);

                    if(config.CreateBlogDirectories)                    
                        Weblogs.CreateBlogDirectory(w);
			

                }
            }
        }
    }
}
